#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>

#include "dtk_timeline.h"
#include "dtk_debug.h"
#include "dtk_master_clock.h"

DTKMasterClock* dtk_mc_create()
{
    DTKMasterClock* mc;

    mc = (DTKMasterClock*)malloc(sizeof(DTKMasterClock));
    memset (mc, 0, sizeof(DTKMasterClock));
    dtk_list_init(DLIST(mc), (DPointer)mc);
    return mc;
}

void dtk_mc_release(DTKMasterClock* self)
{
    if (self == NULL)
    {
        return;
    }
    return;
}

void dtk_mc_add_timeline (DTKMasterClock* self, DTKTimeLine* timeline)
{
    DTK_ASSERT(self != NULL && timeline != NULL);

    dtk_list_prepend (DLIST(self), DLINK(timeline));

    return;
}

void dtk_mc_remove_timeline (DTKMasterClock* self, DTKTimeLine* timeline)
{
    DTK_ASSERT(self != NULL && timeline != NULL);

    dtk_list_remove (DLIST(self), DLINK(timeline));

    return;
}

static mc_active(DList* list, DLink* link, va_list args)
{
    DTKTimeLine* timeline = (DTKTimeLine*)DLINKDATA(link);
    struct timeval* tv;

    tv = va_arg(args, struct timeval*);

    dtk_timeline_do_tick(timeline, tv);
    return DTK_FALSE;
}

void dtk_mc_active(DTKMasterClock* self)
{
    DTKTimeLine *timeline, *next;
    struct timeval tv;

    if (self == NULL)
    {
        return;
    }

    gettimeofday(&tv, NULL);
    dtk_list_foreach(DLIST(self), mc_active, &tv);
    return;
}